const db = require('../db/index');
const nodemailer  = require('nodemailer');
const emailConfig = require('../emailConfig')

exports.reguser = (req,res) =>{
    const userInfo = req.body
    if(!userInfo.username || !userInfo.email|| !userInfo.password){
       return res.send({ status: 0, message: '用户名、邮箱和密码都不能为空！'})
    }
    const sqlStr1 = 'SELECT * FROM users WHERE username = ? OR email = ?'
    db.query(sqlStr1,[userInfo.username, userInfo.email],(error,results)=>{
       if(error) return res.send({ status: 0, message: error.message })
       else if(results.length > 0) return res.send({ status: 400, message: '用户名或邮箱已注册！'})
       else{
          const getMaxIdSql = 'SELECT MAX(id) as maxId FROM users';
          db.query(getMaxIdSql,(err,maxIdResult)=>{
              if(err) return res.send({ status: 0, message: err.message })
              let newId = 1
              if(maxIdResult[0].maxId !== null){
                newId = maxIdResult[0].maxId + 1
              }
              userInfo.id = newId
              const sqlStr2 = 'INSERT INTO users (id,username, email, password) VALUES (?,?,?,?)'
              db.query(sqlStr2,[userInfo.id, userInfo.username, userInfo.email, userInfo.password],(err,result)=>{
                 if(err) return res.send({ status: 0, message: err.message})
                 else if(result.affectedRows !==1 ) return res.send({ status: 0, message: '注册失败！'})
                 res.send({ status: 200, message: '注册成功！'})
              })
          })
       }
    })
}

exports.login = (req,res) =>{
    const userInfo = req.body
    if(!userInfo.password || !userInfo.username|| !userInfo.email){
        return res.send({ status: 0, message: "用户名，邮箱，密码均不能为空！"})
    }
    const sqlStr3 = 'SELECT * FROM users Where username = ?'
    db.query(sqlStr3,userInfo.username,(error,result)=>{
        if(error) return res.send({ status: 0, message: error.message })
        else if(result.length !== 1) return res.send({ status: 0, message: '用户名错误！登录失败！'})
        else{
          const compareResult = userInfo.password === result[0].password || userInfo.email === result[0].email
          if(!compareResult) return res.send({ status: 0, message: '密码或邮箱错误！'})
          else{
            res.send({
                status: 200,
                message: '登录成功！',
                data: result,
                token: 'Bearer A73569843QQJ56YT'
            })
          }
        }
    })
}

// 创建邮件传输器
const transporter = nodemailer.createTransport(emailConfig);

// 生成随机验证码
function generateCode() {
    return Math.floor(100000 + Math.random() * 900000).toString();
}

exports.validCode = (req,res) => {
    const email = req.body.email
    const code = generateCode();
    if (!email) {
        return res.status(400).send({ status: 0, message: '未提供邮箱地址' });
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        return res.status(400).send({ status: 0, message: '邮箱格式不正确' });
    }
    const mailOptions = {
        from: emailConfig.auth.user,
        to: email,
        subject: '验证码',
        text: `您的验证码是：${code}`
    };
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.log(error);
            res.send({ status: 0, message: error.message });
        } else {
            console.log('邮件已发送: ' + info.response);
            res.send({ status: 200, message: '验证码发送成功！', code });
        }
    });
}